package com.maoslv.controller;

import com.maoslv.aop.LogAnnotation;
import com.maoslv.dto.Result;
import com.maoslv.pojo.Goods;
import com.maoslv.pojo.Pagination;
import com.maoslv.service.good.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RequestMapping("goods")
@Scope("request")
@RestController
public class GoodsController {
    @Autowired
    GoodsService goodsService;

    @LogAnnotation(operator = "获取商品列表")
    @PostMapping("list")
    @PreAuthorize("hasAnyAuthority('goods:list')")
    public Result getGoodsList(@RequestBody Pagination pagination) {
        Map<String,Object> result = goodsService.getGoodsList(pagination);
        if (result != null) {
            return Result.succ("获取成功", result);
        }
        return Result.fail("获取失败");
    }

    @LogAnnotation(operator = "新增商品上架")
    @PostMapping("add")
    @PreAuthorize("hasAnyAuthority('goods:add')")
    public Result addGoods(@RequestBody Goods goods) {
        if (goodsService.addGoods(goods) > 0) {
            return Result.succ("新增成功", null);
        }
        return Result.fail("新增失败");
    }

    @LogAnnotation(operator = "获取商品信息")
    @GetMapping("info/{id}")
    @PreAuthorize("hasAnyAuthority('goods:update')")
    public Result getGoodsInfo(@PathVariable Integer id) {
        Goods goods = goodsService.getGoodsInfo(id);
        if (goods != null) {
            return Result.succ("获取成功", goods);
        }
        return Result.fail("获取失败");
    }

    @LogAnnotation(operator = "编辑商品")
    @PostMapping("/update")
    @PreAuthorize("hasAnyAuthority('goods:update')")
    public Result updateGoods(@RequestBody Goods goods) {
        if (goodsService.updateGoods(goods) > 0) {
            return Result.succ("编辑成功", null);
        }
        return Result.fail("编辑失败");
    }

    @LogAnnotation(operator = "获取商品购物车列表")
    @GetMapping("/shopcar")
    public Result getShopCarGoods() {
        List<Goods> shopCarGoods = goodsService.getShopCarGoods();
        if (shopCarGoods != null) {
            return Result.succ("获取成功", shopCarGoods);
        }
        return Result.fail("获取失败");
    }

    @PostMapping("/batch_update")
    public Result batchUpdateGoods(@RequestBody List<Goods> goodsList) {
        if (goodsService.batchUpdateGoods(goodsList) > 0) {
            return Result.succ("提交订单成功，请等待审核", null);
        }
        return Result.fail("提交失败");
    }
}
